<template>
  <div>
    <van-nav-bar title="城市选择" left-arrow @click-left="$router.back()" />
    <van-index-bar
      highlight-color="#21b97a"
      :index-list="indexList"
      >
    <div>
      <van-index-anchor index="#">当前城市</van-index-anchor>
          <van-cell title="北京">{{  }}</van-cell>
    </div>
      <div>
        <van-index-anchor index="热">热门城市</van-index-anchor>
            <van-cell :title='el.label' v-for="(el,i) in hotCity" :key="i" @click="handleClick"></van-cell>
      </div>
      <div v-for="item,index in cityName" :key="index">
          <van-index-anchor :index="index" ></van-index-anchor>
        <van-cell :title="el.label" v-for="el,index in item" :key="index" @click="handleClick"></van-cell>
      </div>
    </van-index-bar>
  </div>
</template>
<script>
import { getCity, getHotCity } from '@/api/area'
import { Toast } from 'vant'
export default {
  name: 'CityPage',
  components: {},
  props: {},
  data () {
    return {
      cityList: [],
      indexSpecial: ['#', '热'],
      indexList: [],
      cityName: {},
      hotCity: []
      // indexList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    }
  },
  watch: {},
  computed: {},
  created () {
    this.getCity()
  },
  mounted () {},
  methods: {
    async getCity () {
      // 获取所有城市
      const { data: { body } } = await getCity()
      // 将所有数据按字母排序
      this.cityList = body.sort((a, b) => {
        const shortA = a.short.toUpperCase()
        const shortB = b.short.toUpperCase()
        if (shortA < shortB) {
          return -1
        }
        if (shortA > shortB) {
          return 1
        }
        return 0
      })
      // 获取城市字母并去重
      this.cityList.forEach((item, i) => {
        const str = item.short[0].toUpperCase()
        this.indexList.push(str)
      })
      this.indexList = [...new Set(this.indexList)]
      this.indexList.unshift(...this.indexSpecial)
      // console.log(this.indexList)
      // 将数据重新排列
      this.cityList.forEach(el => {
        const letter = el.short[0].toUpperCase()
        if (!(letter in this.cityName)) {
          this.cityName[letter] = []
        }
        this.cityName[letter].push(el)
      })
      // 获取热门城市数据
      const res = await getHotCity()
      this.hotCity = res.data.body
      // const hot = { 热: this.hotCity }
      // console.log(hot)
      // this.cityName.unshift(hot)
      // console.log(this.cityName)
    },
    handleClick (e) {
      const res = this.hotCity.find(el => el.label === e.target.innerText)
      if (!res) return Toast('该城市暂无房源数据')
      this.$router.push('/home')
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.van-index-bar__index {
  margin: 0 10px 5px 0;
  padding: 0;
  font-size: 14px;
}
.van-cell {
  background-color: #fff;
}
/deep/.van-index-anchor{
  color: #999999;
  font-size: 14px;
}
</style>
